import React, {useCallback, useEffect, useState} from "react";
import {Menu} from "antd"
import {menusConfig, MenuConfig} from "./menus"
import {Navigation, useCurrentRoute, findDeep} from "f22";
import {MenuProps} from "antd/lib/menu"

const {SubMenu} = Menu;

enum ThemeEnum {
  LIGHT = "light",
  DARK = "dark"
}

export default () => {
  const [theme] = useState<string>(ThemeEnum.DARK)
  const [menus] = useState(menusConfig)
  const [menusPath, setMenusPath] = useState<string[]>([])
  const router = useCurrentRoute();

  useEffect(() => {
    if (!router) return
    const result = findDeep(router?.path, menusConfig, "to")
    const newMenusPath = result[1]
    const newMenusStringPath = newMenusPath.map(item => item + "")
    setMenusPath(newMenusStringPath)
  }, [router])

  const handleClick: MenuProps['onClick'] = ({key, keyPath}) => {
    setMenusPath(keyPath as string[]);
    const keyArray: number[] = (key as string).split("-").map((item: string) => parseInt(item));
    let item: MenuConfig = {
      icon: null,
      name: "",
      children: menusConfig
    };
    for (let i of keyArray) {
      // @ts-ignore
      item = item.children[i]
    }
    Navigation.push(item.to as string)
  };

  return (
    <Menu
      theme={theme as (ThemeEnum.DARK | ThemeEnum.LIGHT)}
      onClick={handleClick}
      style={{marginTop: -4}}
      selectedKeys={[menusPath.join("-")]}
      mode="inline"
    >
      {
        menus.map((item, index) => {
          const Icon = item.icon
          if (item.children) {
            return (
              <SubMenu
                key={`${index}`}
                title={
                  <span>  {!!Icon ? <Icon/> : null}
                    <span>{item.name}</span>
                                        </span>
                }
              >
                {
                  item.children.map((child, childIndex) => {
                    const Icon = child.icon;
                    return <Menu.Item key={`${index}-${childIndex}`}>
                                                   <span>
                                                     {!!Icon ? <Icon/> : null}
                                                     <span>{child.name}</span>
                                        </span>
                    </Menu.Item>
                  })
                }
              </SubMenu>
            )
          }
          return <Menu.Item key={`${index}`}>
                               <span>
                                  {!!Icon ? <Icon/> : null}
                                 <span>{item.name}</span>
                                        </span>
          </Menu.Item>
        })
      }
    </Menu>
  )
}
